package com.guguskins.back.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guguskins.back.common.exception.GlobalException;
import com.guguskins.back.common.helper.MenuHelper;
import com.guguskins.back.common.helper.PermissionHelper;
import com.guguskins.back.entity.GuPermission;
import com.guguskins.back.mapper.GuPermissionMapper;
import com.guguskins.back.service.GuAdminUserService;
import com.guguskins.back.service.GuPermissionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 * 权限 服务实现类
 * </p>
 *
 * @author mybatis-plus
 * @since 2021-07-16
 */
@Service
@Slf4j
public class GuPermissionServiceImpl extends ServiceImpl<GuPermissionMapper, GuPermission> implements GuPermissionService {

    @Autowired
    private GuPermissionMapper permissionMapper;

    @Autowired
    private GuAdminUserService adminUserService;

    @Override
    public List<String> selectPermissionValueByUserId(Integer userId) {
        List<String> selectPermissionValueList = null;
        if (adminUserService.isSysAdmin(userId)) {
            //如果是系统管理员，获取所有权限
            selectPermissionValueList = permissionMapper.selectAllPermissionValue();
        } else {
            selectPermissionValueList = permissionMapper.selectPermissionValueByUserId(userId);
        }
        return selectPermissionValueList;
    }


    @Override
    public List<GuPermission> selectPermissionByUserId(Integer userId, boolean route) {
        List<GuPermission> selectPermissionList = null;
        if (adminUserService.isSysAdmin(userId)) {
            //如果是超级管理员，获取所有菜单
            selectPermissionList = permissionMapper.selectList(new QueryWrapper<GuPermission>() {
                {
                    eq("status", 1);
                    eq("is_deleted", 0);
                    ne(!route, "type", 2);
                    isNotNull(route, "component");
                    orderByAsc("sort");
                }
            });
        } else {
            selectPermissionList = permissionMapper.selectPermissionByUserId(userId, route);
        }
        return selectPermissionList;

    }

    @Override
    public List<JSONObject> selectPermissionTreeByUserId(Integer userId, boolean route) {
        List<GuPermission> selectPermissionList = selectPermissionByUserId(userId, route);
        List<GuPermission> permissionList = PermissionHelper.build(selectPermissionList);
        List<JSONObject> result = MenuHelper.build(permissionList);
        return null;
    }

    @Override
    public int add(GuPermission permissionEntity) {
        GuPermission permission = permissionMapper.selectOne(new QueryWrapper<GuPermission>() {
            {
                eq("pid", permissionEntity.getPid());
                eq("title", permissionEntity.getTitle());
            }
        });
        if (permission != null) {
            throw new GlobalException("权限标题已存在");
        }


        return permissionMapper.insert(permissionEntity);
    }

    @Override
    public int edit(GuPermission permissionEntity) {
        GuPermission permission = permissionMapper.selectOne(new QueryWrapper<GuPermission>() {
            {
                eq("pid", permissionEntity.getPid());
                eq("title", permissionEntity.getTitle());
                ne("id", permissionEntity.getId());
            }
        });
        if (permission != null) {
            throw new GlobalException("权限标题已存在");
        }


        return permissionMapper.updateById(permissionEntity);
    }

    @Override
    public int updateStatus(Integer[] id, int status) {
        List<Integer> collect = Stream.of(status).collect(Collectors.toList());
        List<GuPermission> permissions = permissionMapper.selectBatchIds(collect);
        AtomicInteger count = new AtomicInteger();
        permissions.forEach(permission -> {
            permission.setStatus(status);

            int result = permissionMapper.updateById(permission);
            count.addAndGet(result);
            if (result < 0) {
                log.error("权限{}，{}失败", permission.getId(), status == 1 ? "启用" : "禁用");
            }
        });
        return count.get();
    }

    @Override
    public List<GuPermission> queryAllMenu() {
        List<GuPermission> permissions = permissionMapper.selectList(new QueryWrapper<GuPermission>() {
            {
                orderByAsc("sort");
            }
        });
        List<GuPermission> result = PermissionHelper.build(permissions);
        return result;
    }

    private String getComponent(String path) {
        String[] split = path.split("/");
        String one = split[split.length - 2];
        one = one.substring(0, 1).toUpperCase() + one.substring(1);
        String two = split[split.length - 1];
        two = two.substring(0, 1).toUpperCase() + two.substring(1);
        String component = one + two;
        return component;
    }
}
